package com.xone.xapp;

import java.util.List;
import java.util.Locale;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;

public class GuideGridAdapter extends BaseAdapter {
	
	protected Context context;
	protected List<JSONObject> list;
	protected int imageWidth;
	
	public GuideGridAdapter(Context context, List<JSONObject> list, int imageWidth) {
		this.context = context;
		this.list = list;
		this.imageWidth = imageWidth;
	}

	@Override
	public int getCount() {
		if (null == list || list.isEmpty()) {
			return 0;
		}
		return list.size();
	}

	@Override
	public JSONObject getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		JSONObject object = list.get(position);
		String linkNo = null;
		linkNo = JSONUtils.getStringFromJSONObject(object, "linkNo");
		if (null != linkNo) {
			linkNo = linkNo.toLowerCase(Locale.ENGLISH);
		}
		ImageView imageView;
		if (convertView == null) {
			imageView = new ImageView(context);
		} else {
			imageView = (ImageView) convertView;
		}
		imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		imageView.setAdjustViewBounds(true);
		final int resId = ContextUtils.getResourceId(context, linkNo, "drawable");
		imageView.setImageResource(resId);
		final String id = linkNo;
		imageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if ("A012".equalsIgnoreCase(id)) {//客服电话
					Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Constants.CUSTOMER_TEL));
					context.startActivity(i);
					return;
				}
				Class<? extends Activity> activity = GuideImageRoute.IMAGE_ROUTE.get(resId);
				if (null != activity) {
					Intent i = new Intent(context, activity);
					Bundle pBundle = GuideImageRoute.IMAGE_EXTRA.get(resId);
					if (null != pBundle) {
						i.putExtras(pBundle);
					}
					context.startActivity(i);
				} else {
					Toast.makeText(context, "请给编号" + id + "增加活动", Toast.LENGTH_SHORT).show();
				}
			}
		});
		return imageView;
	}

}
